package com.ai.bitcoin.controller;

import com.ai.bitcoin.annotation.Privilege;
import com.ai.bitcoin.bo.SubCoinRequestParam;
import com.ai.bitcoin.constant.CodeConstant;
import com.ai.bitcoin.exception.BusinessException;
import com.ai.bitcoin.input.GeneralRequest;
import com.ai.bitcoin.input.RequestHepler;
import com.ai.bitcoin.jpa.dao.BccUserCustomDao;
import com.ai.bitcoin.jpa.dao.ParameterDao;
import com.ai.bitcoin.jpa.entity.BccUser;
import com.ai.bitcoin.jpa.entity.BccUserBonusConfig;
import com.ai.bitcoin.jpa.entity.BccUserCustom;
import com.ai.bitcoin.jpa.entity.Parameter;
import com.ai.bitcoin.jpa.service.UserBonusService;
import com.ai.bitcoin.output.GeneralReponse;
import com.ai.bitcoin.service.UserService;
import com.ai.bitcoin.service.WeiXinService;
import com.ai.bitcoin.util.IpUtil;
import com.ai.bitcoin.utils.JsonUtils;
import com.ai.bitcoin.vo.UserEncourageReq;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController extends CommonController {

    @Value("${asyncTimeout}")
    long asyncTimeout;

    @Autowired
    private UserService userService;

    @Autowired
    private BccUserCustomDao userCustomDao;

    @Autowired
    private ParameterDao parameterDao;

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private UserBonusService userBonusService;

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handleException(HttpServletRequest request,
                                                  HttpServletResponse response, RuntimeException e) {
        log.info("", e);
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("SERVICE_UNAVAILABLE");
    }

    @Privilege
    @GetMapping(value = "/custom", produces = "application/json;charset=UTF-8")
    public String getCustom(final HttpServletRequest request) throws BusinessException {
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        Parameter para = parameterDao.findByParameterKey("DEFAULT_USER_CUSTOM_LIKE")
                .orElseThrow(() -> new BusinessException("未配置默认值DEFAULT_USER_CUSTOM_LIKE"));
        String[] result = StringUtils.split(para.getParameterValue(), ",");
        if (generalRequest.getUser() != null) {
            BccUserCustom userCustom = userCustomDao.findByUserIdAndTypeCd(generalRequest.getUser().getId(), BccUserCustom.TYPE_BCC_LIKE);
            if (userCustom != null) {
                result = StringUtils.split(userCustom.getContent(), ",");
            }
        }
        return JsonUtils.toJson(Lists.newArrayList(result));
    }

    @Privilege
    @PostMapping(value = "/custom", produces = "application/json;charset=UTF-8")
    public List<String> updateCustom(final HttpServletRequest request, @RequestParam String content) throws BusinessException {
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        if (generalRequest.getUser() == null) {
            throw new BusinessException("用户未登录");
        }
        BccUserCustom userCustom = userCustomDao.findByUserIdAndTypeCd(generalRequest.getUser().getOpenId(), BccUserCustom.TYPE_BCC_LIKE);
        if (userCustom == null) {
            userCustom = new BccUserCustom();
            userCustom.setUserId(generalRequest.getUser().getId());
            userCustom.setTypeCd(BccUserCustom.TYPE_BCC_LIKE);
            userCustom.setInsertDate(new Date());
        }
        userCustom.setUpdateDate(new Date());
        userCustom.setContent(content);
        userCustomDao.save(userCustom);
        return Lists.newArrayList(StringUtils.split(content, ","));
    }

    @RequestMapping(value = "/loginQrcode", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> loginQrcode(final HttpServletRequest request) {
        String ip = IpUtil.getClientIp(request);
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralReponse response = userService.generateQrcode(ip);
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }

    @RequestMapping(value = "/qrcodeLoginPing", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> qrcodeLoginPing(final HttpServletRequest request, @RequestParam("key") String key) {
        String ip = IpUtil.getClientIp(request);
        if (log.isDebugEnabled()) {
            log.debug("qrcodeLoginPing circle ip-->{}", ip);
        }
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        userService.queryIfLogin(key, deferredResult);
        return deferredResult;
    }

    @RequestMapping(value = "/wxinfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> wxinfo(final HttpServletRequest request, @RequestParam("code") String code, @RequestParam("state") String state) throws BusinessException {
        long startTime = System.currentTimeMillis();
        if (code == null || StringUtils.isBlank(code)) {
            throw new BusinessException(CodeConstant.PARAM_ERROR,
                    "code is error");
        }
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralReponse response = weiXinService.wxinfo(code, state);
        long endTime = System.currentTimeMillis();
        long spendSeconds = (endTime - startTime) / 1000;
        log.info("【UserController#wxinfo 耗时：{} 秒】", spendSeconds);
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }

    @Privilege
    @RequestMapping(value = "/info", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> info(final HttpServletRequest request) {
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralReponse response = userService.info(generalRequest.getUser().getSymbol());
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }

    //用户订阅币
    @Privilege  //time：订阅多长时间 一个月1积分
    @RequestMapping(value = "/sub", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> sub(final HttpServletRequest request, @RequestBody SubCoinRequestParam subCoinRequestParam) throws BusinessException {
        if (subCoinRequestParam.getBccId() == null || StringUtils.isBlank(subCoinRequestParam.getBccId())) {
            throw new BusinessException(CodeConstant.PARAM_ERROR, "bccId is empty");
        }
        if (subCoinRequestParam.getTime() == null || subCoinRequestParam.getTime() <= 0) {
            throw new BusinessException(CodeConstant.PARAM_ERROR, "time is empty");
        }
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        BccUser user = generalRequest.getUser();
        GeneralReponse response = userService.sub(user.getSymbol(), subCoinRequestParam.getBccId(), subCoinRequestParam.getTime(), user.getOpenId());
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }

    //用户订阅币的信息
    @Privilege
    @RequestMapping(value = "/record/sub", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> recordsub(final HttpServletRequest request) {
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        GeneralReponse response = userService.subrecord(generalRequest.getUser().getOpenId());
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }

    //用户订阅币的记录
    @Privilege
    @RequestMapping(value = "/record/subaction", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> recordsubaction(final HttpServletRequest request) {
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralReponse response = userService.subaction(generalRequest.getUser().getSymbol());
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }

    //用户订阅套餐的记录
    @Privilege
    @RequestMapping(value = "/record/package", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> pack(final HttpServletRequest request) {
        GeneralRequest generalRequest = RequestHepler.processRequest(request);
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralReponse response = userService.pack(generalRequest.getUser().getSymbol());
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }

    //用户plc激励
    @RequestMapping(value = "/encourage", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> plcEncourage(final HttpServletRequest request, UserEncourageReq userEncourageReq) {
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        String sourceTypeCd = BccUserBonusConfig.EVENT_SOURCE_SHARE;
        String eventTypeCd = null;
        if (userEncourageReq.getType() == 1) { //阅读文章
            if (StringUtils.isNotEmpty(userEncourageReq.getArticleOpenId())) {
                try {
                    UserEncourageReq shareUserRequest = (UserEncourageReq) BeanUtils.cloneBean(userEncourageReq);
                    //置换OpenId
                    shareUserRequest.setOpenId(userEncourageReq.getArticleOpenId());
                    shareUserRequest.setArticleOpenId(userEncourageReq.getOpenId());
                    //分享被阅读奖励
                    userBonusService.sendBonus(sourceTypeCd, "0302", shareUserRequest);
                } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException ignored) {
                }

            }
            //阅读奖励
            eventTypeCd = "0301";
        }
        else if (userEncourageReq.getType() == 5) { //分享
            //分享奖励
            eventTypeCd = "0305";
        }
        else if (userEncourageReq.getType() == 10) {//看PLC视频
            eventTypeCd = "0304";
        }
        else if (userEncourageReq.getType() == 11) {//看示例视频
            eventTypeCd = "0303";
        }
        else if (userEncourageReq.getType() == 12) {//固定时长奖励
            eventTypeCd = "0312";
        }
        if (StringUtils.isNotEmpty(eventTypeCd)) {
            userBonusService.sendBonus(sourceTypeCd, eventTypeCd, userEncourageReq);
            return deferredContent(deferredResult, JSONObject.fromObject(new GeneralReponse(CodeConstant.SUCCESS, null)));
        }
        else {
            return deferredContent(deferredResult, JSONObject.fromObject(new GeneralReponse(CodeConstant.BUSINESS_ERROR, null)));
        }

    }
}
